const OpenAI = require("openai");

// 初始化 openai 客户端
const openai = new OpenAI({
  apiKey: "sk-c189816639d742a2b564affc08758b9a", // 从环境变量读取
  baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
});

async function filter(val) {
  let reasoningContent = "";
  let answerContent = "";
  let isAnswering = false;

  let messages = [
    {
      role: "user",
      content: [],
    },
  ];
  // const val = [
  //   "https://img.alicdn.com/imgextra/i1/385132127/O1CN01qnzLo21RaDU1d9GfK_!!385132127.jpg",
  //   "https://img.alicdn.com/imgextra/i3/385132127/O1CN01qKoRm61RaDTVWqs9E_!!385132127.jpg",
  //   "https://img.alicdn.com/imgextra/i4/385132127/O1CN016TrhqB1RaDU0Cd7Tv_!!385132127.jpg",
  //   "https://img.alicdn.com/imgextra/i3/385132127/O1CN01Ggk4ZA1RaDU1Iyoht_!!385132127.jpg",
  // ];
  // https://img.alicdn.com/imgextra/i1/385132127/O1CN01qnzLo21RaDU1d9GfK_!!385132127.jpg,https://img.alicdn.com/imgextra/i3/385132127/O1CN01qKoRm61RaDTVWqs9E_!!385132127.jpg,https://img.alicdn.com/imgextra/i4/385132127/O1CN016TrhqB1RaDU0Cd7Tv_!!385132127.jpg,https://img.alicdn.com/imgextra/i3/385132127/O1CN01Ggk4ZA1RaDU1Iyoht_!!385132127.jpg,https://img.alicdn.com/imgextra/i3/693060164/O1CN01ZioTqN1D5A0Ts5hnt_!!693060164.jpg
  const text = [
    {
      type: "text",
      text: "找出这些图片里面含有尺码表的图片，返回符合的图片位置，只要数字，比如1 或者2 3 4这种的,如果没有类似的图片，那就返回空字符串",
    },
  ];
  const imgList = val.map((item) => {
    return {
      type: "image_url",
      image_url: {
        url: item,
      },
    };
  });

  messages[0].content = [...imgList, ...text];

  try {
    const stream = await openai.chat.completions.create({
      model: "qvq-max",
      messages: messages,
      stream: true,
    });

    const response = "";
    for await (const chunk of stream) {
      if (!chunk.choices?.length) {
        continue;
      }

      const delta = chunk.choices[0].delta;

      // 处理思考过程
      if (delta.reasoning_content) {
        process.stdout.write(delta.reasoning_content);
        reasoningContent += delta.reasoning_content;
      }
      // 处理正式回复
      else if (delta.content) {
        if (!isAnswering) {
          isAnswering = true;
        }
        answerContent += delta.content;
      }
    }
    return answerContent ? val[Number(answerContent) - 1] : "";
  } catch (error) {
    console.error("Error:", error);
  }
}

module.exports = {
  filter,
};
